<template>
    <div>
       <div class="warpper-boxs" style="margin-bottom:15px">
        <detail-list :col="4">
          <detail-list-item term="关联园区名称">{{detail.parkName}}</detail-list-item>
        </detail-list>
        <detail-list :col="4">
          <detail-list-item term="当月开票次数">{{detail.monthCount}}</detail-list-item>
          <detail-list-item term="当月开票总金额">{{detail.monthAmount}}</detail-list-item>
          <detail-list-item term="历史开票次数">{{detail.totalCount}}</detail-list-item>
          <detail-list-item term="历史开票总金额">{{detail.totalAmount}}</detail-list-item>
        </detail-list>
       </div>
      
      <div class="warpper-box">
        <form-create 
          class="custom-select"
          v-model="params.fApi" 
          :rule="params.rule" 
          :option="params.option"
          @btn-back-click="$router.back()"
          @btn-search-click="loadTable(true)"
          @btn-reset-click="reset"/>
          
        <a-card
          style="margin-top: 24px"
          :bordered="false"
          :tabList="tabData"
          :activeTabKey="activeTabKey"
          @tabChange="callbackTab">
          <template #tabBarExtraContent>
            <span v-if="activeTabKey==='-1'">
              <a-button type="primary" v-action:billingAddBtn icon="plus" @click="addBilling">新增开票</a-button>
            </span>
          </template>
          <a-alert v-if="tis" :message="tis" type="success" show-icon />
          <a-table 
          :columns="table.columns"
          size="middle"
          :pagination="table.pagination"
          :rowSelection="state ? rowSelection : undefined"
          @change="handleTableChange"
          rowKey="id"
          :data-source="table.loadData">
            <span slot="action" slot-scope="text, record">
              <span v-if="activeTabKey=='2'">
                <a-popconfirm
                  title="确认取消开票？更新状态为未开票状态"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="closeBilling(record)" >
                   <a v-action:billingColseBtn>取消开票</a>
                   <a-divider v-action:billingColseBtn type="vertical" />
              </a-popconfirm>
              </span>
              <a v-if="activeTabKey!=='-1'" @click="details(record)">查看详情</a>
            </span>
          </a-table>
        </a-card>
    </div>

    <billing-add ref="createForm" @ok="billingOk"/>
    <invoice-detail ref="createDetail"/>

  </div>
</template>

<script>
import { mapGetters,mapActions} from 'vuex'
import DetailList from '@/components/tools/DetailList'
const DetailListItem = DetailList.Item
import {
    PARAMS_BILLING_DETAIL,
    COLUMNS_NO_BILLING,
    COLUMNS_OTHER_BILLING,
    EN_BILLING_TAB,
    OPTION_BLOCK,
    OPTION_INLINE
} from './form'
import { 
  allGetBillingStateList,
  allGetBillingEnterpriseList,
  allGetBillingStatis,
  billingCancel,
  billingDetail,
  billingOperate
} from '@/api/manage/billing'
import BillingAdd from './billing_add'
import InvoiceDetail from './invoice_detail'
export default {
  name: 'billingDetail',
  components: {
    DetailList,
    DetailListItem,
    BillingAdd,
    InvoiceDetail
  },
  data () {
    return {
      activeTabKey:'-1',
      params:{
        fApi:{},
        rule:PARAMS_BILLING_DETAIL,
        option:OPTION_INLINE
      },
      table:{
        columns:[],
        loadData:[],
        pagination:{
          current:1,
          pageSize: 10,
          total:0,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      detail:{
        monthCount:0,
        monthAmount:0,
        totalCount:0,
        totalAmount:0,
        enterpriseName:'',
        parkName:''
      },
      tabData:EN_BILLING_TAB,
      selectedRowKeys:[],
      tis:''
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    state(){
      var flag = false;
      if(this.userInfo.type === 2){
          if(this.activeTabKey === '-1'){
              flag = true;
          }
      }
      return flag;
    },
    rowSelection(){
        return {
            selectedRowKeys:this.selectedRowKeys,
            fixed:true,
            onChange:this.onSelectChange
        }
    }
  },
  created () {
    let nowDate = new Date();
    const time =  nowDate.getFullYear() + "-0" + (nowDate.getMonth()+1);
    this.$nextTick(()=>{
      this.params.fApi.setValue({'time':time})
    })
    this.generateRoutes();
    this.initColumns();
    this.initStatis();
  },
  methods: {
    ...mapActions({
      generateRoutes:'generateRoutes'
    }),
    initColumns(){
      if(this.activeTabKey === '-1'){
        this.table.columns = COLUMNS_NO_BILLING;
      }else{
        let billingKey = this.userInfo.roleFiledAuthorities.billingKey;
        if(billingKey && billingKey.length >= 1){
          this.table.columns = COLUMNS_OTHER_BILLING.filter(v=> !billingKey.includes(v.dataIndex));
        }else{
          this.table.columns = COLUMNS_OTHER_BILLING;
        }
      }
       this.loadTable(true);
    },
    onSelectChange(selectedRowKeys, rows) {
        this.selectedRowKeys = selectedRowKeys;
        this.tis="已选择 "+selectedRowKeys.length+" 项";
        if(selectedRowKeys.length==0){
          this.tis ='';
          this.selectedRowKeys = [];
        }
    },
    async initStatis(){
      let params = {};
      params.parkId = this.$route.query.parkId;
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const {code,data} = await allGetBillingStatis(params);
      if(code === '1'){
        if(data && data != null){
          for(var key in data){
            this.detail[key] = data[key];
          }
        }
      }
    },
    async loadTable(flag){
       let params = {};
      if(JSON.stringify(this.params.fApi) !== "{}"){
        const formData = this.params.fApi.formData();
        params.time = formData.time;
        params.batchCode = formData.batchCode;
        params.batchName = formData.batchName;
      }
      if(JSON.stringify(this.params.fApi) === "{}"){
          let nowDate = new Date();
          params.time =  nowDate.getFullYear() + "-0" + (nowDate.getMonth()+1);
      }
      if(flag){
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.status = '';
      if(this.activeTabKey !== '-1'){
        params.status = this.activeTabKey;
      }
       params.parkId = this.$route.query.parkId;
       params.pageNum = this.table.pagination.current;
       params.pageSize = this.table.pagination.pageSize;
        const {code,data} = this.activeTabKey === '-1' ? await allGetBillingEnterpriseList(params) : await allGetBillingStateList(params);
        if(code ==='1'){
          var resDtoList = [];
          data.content.forEach(v=>{
            resDtoList = v.resDtoList;
          })
          if(resDtoList && resDtoList.length >= 1){
            this.table.loadData = resDtoList;
          }else{
            this.table.loadData = data.content;
          }
          this.table.pagination.total = data.total || 0;
        }
    },
    handleTableChange(pagination){
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    callbackTab(key){
      this.activeTabKey = key;
      this.initColumns();
      this.tis ='';
        this.selectedRowKeys = [];
      this.loadTable(false);
    },
    addBilling(){
      if(this.selectedRowKeys.length ===0){
        return this.$message.error('请勾选开票批次');
      }
      const settleBatchCode = [];
      this.table.loadData.forEach(v=>{
          if(this.selectedRowKeys.indexOf(v.id) != -1){
              settleBatchCode.push(v.settleBatchCode);
          }
      })
      const ids = settleBatchCode.join(',');
      this.$refs.createForm.add(ids)
    },
    details(rows){
      this.$refs.createDetail.invoiceDetail(rows)
    },
    reset(){
      this.params.fApi.setValue({
        "time":"",
        "batchCode":"",
        "batchName":""
      })
      this.loadTable(true);
    },
    async closeBilling(rows){
      let params = {id:rows.id,category:rows.category,status:5,type:rows.type};
      const {code} = await billingOperate(params);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(true);
      }
    },
    billingOk(){
      this.tis ='';
      this.selectedRowKeys = [];
      this.loadTable(true);
    }
  }
}
</script>
